package org.southyin.securitysamples.controller;

import com.github.pagehelper.PageInfo;
import org.southyin.securitysamples.commons.CommonsResp;
import org.southyin.securitysamples.model.Customer;
import org.southyin.securitysamples.service.CustomerService;
import org.southyin.securitysamples.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerService customerService;

    @GetMapping("/")
    public PageInfo listCustomers(String keyWords, @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize) {
        return customerService.listCustomers(keyWords,pageNum,pageSize);
    }

    @GetMapping("/exportExcel")
    public ResponseEntity<byte[]> exportExcel(String keyWords) {
        PageInfo<Customer> pageInfo = customerService.listCustomers(keyWords, null, null);
        List<Customer> list = pageInfo.getList();
        return POIUtils.exportExcel(list);
    }

    @PostMapping("/importExcel")
    public CommonsResp importExcel(MultipartFile file) {
        List<Customer> customerList = POIUtils.importExcel(file);
        if (customerList.size() == 0) {
            return CommonsResp.failed(500,"上传失败,没有数据可以上传");
        }
        int count = customerService.multiInsertCustomers(customerList);
        if (count != customerList.size()) {
            return CommonsResp.failed(500,"上传失败");
        }
        return CommonsResp.succeess(200,"上传成功");
    }
}
